/**
 * Copyright 2016 JustWayward Team
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taptech.doufu.ui.view.readview.util;


import com.taptech.doufu.constant.Constant;

import java.io.File;
import java.io.IOException;

/**
 * 缓存工具类
 */
public class CacheManager {

    private static CacheManager manager;

    public static CacheManager getInstance() {
        return manager == null ? (manager = new CacheManager()) : manager;
    }

    public File getChapterFile(String bookId, int chapter) {
        File file = FileUtils.getChapterFile(bookId, chapter);
        if (file != null && file.length() > 50)
            return file;
        return null;
    }

    public void deletNovelFileById(String bookId) {
        File file = FileUtils.getBookDir(bookId);
        if (file.exists()) {
            try {
                FileUtils.deleteFile(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void saveChapterFile(String bookId, int chapter, String data,int indentType) {
        File file = FileUtils.getChapterFile(bookId, chapter);
        FileUtils.writeFile(file.getAbsolutePath(), formatContent(data,indentType), false);
    }

    /**
     * 格式化小说内容。
     * <p/>
     * <li>小说的开头，缩进2格。在开始位置，加入2格空格。
     * <li>所有的段落，缩进2格。所有的\n,替换为2格空格。
     *
     * @param str
     * @return
     */
    public static String formatContent(String str,int indentType) {
        str = str.replaceAll("\\p{Blank}{2,}", "");
//        str = str.replaceAll("[ ]*", "");//替换来自服务器上的，特殊空格
//        str = str.replaceAll("[ ]*", "");//
        str = str.replace("\r","\n");
        str = str.replace("\n\n", "\n");
        str = str.replace("\n\n", "\n");
        str = formatIndent(str, indentType);
//        str = BCConvert.bj2qj(str);
        return str;
    }

    public static String formatIndent(String str, int indentType) {
        if (indentType == Constant.ReadIndentType.FORMAT) {
            str = str.replace("\n", "\n" + getTwoSpaces());
            str = getTwoSpaces() + str;
        }
        return str;
    }


    /**
     * Return a String that only has two spaces.
     *
     * @return
     */
    public static String getTwoSpaces() {
        return "\u3000\u3000";
    }

    public static String getOneSpaces() {
        return "\u3000\u3000";
    }
}
